package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * ShoppingCartServiceImpl
 *
 * @author liliudong
 * @version 1.0
 * @description
 * @date 2023/6/25 15:06
 */
@Service
@RequiredArgsConstructor
public class ShoppingCartServiceImpl implements ShoppingCartService {

    private final ShoppingCartMapper shoppingCartMapper;

    private final DishMapper dishMapper;

    @Override
    public void joinCart(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);

        Dish dish = dishMapper.selectById(shoppingCartDTO.getDishId());

        shoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCart.setName(dish.getName());
        shoppingCart.setNumber(1);
        shoppingCart.setAmount(dish.getPrice());
        shoppingCart.setImage(dish.getImage());
        shoppingCart.setCreateTime(LocalDateTime.now());

        shoppingCartMapper.insert(shoppingCart);
    }

    @Override
    public void sub(ShoppingCartDTO shoppingCartDTO) {
        shoppingCartMapper.deleteByUserIdAndDishIdOrSetmealId(BaseContext.getCurrentId(),
                shoppingCartDTO.getDishId(), shoppingCartDTO.getSetmealId());
    }

    @Override
    public List<ShoppingCart> list() {
        return shoppingCartMapper.listByUserId(BaseContext.getCurrentId());
    }

    @Override
    public void clean() {
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
    }
}
